package com.baitiaojun.excel.core.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class DateConverter implements Converter<Date> {

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Class<?> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        Date date = null;
        if (CellDataTypeEnum.STRING.equals(cellData.getType())) {
            String value = cellData.getStringValue();
            value = value.replaceAll("/", "-");
            if (value.length() <= 10) {
                value = value + "00:00:00";
            }
            try {
                date = SIMPLE_DATE_FORMAT.parse(value);
            } catch (Exception exception) {
                log.warn("时间转换异常, 原因: {}", exception.getMessage());
            }
        }
        return date;
    }

    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(SIMPLE_DATE_FORMAT.format(value));
    }
}
